package com.whynot.frame.basic.controller;


import com.whynot.frame.basic.common.model.APIBase;
import com.whynot.frame.basic.common.model.ErrorCode;
import com.whynot.frame.basic.util.OSSClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 描述: 通过oss的上传图片
 * 作者: chenyao
 * 日期: 2018-01-30.
 * 项目名称: curtain-whynot-basic
 * 版本: 1.0.0
 * JDK: since 1.8
 */
@RestController
@RequestMapping(value="/bdApiCommonUtil")
@Api(value = "oss",description = "Oss上传图片的基础Rest接口")
public class OssUtilController {

    private static final Logger logger = LoggerFactory.getLogger(OssUtilController.class);

    private static final OSSClientUtils ossClientUtils = new OSSClientUtils();

    /**
     * 单图片上传文件
     * @param file
     * @param dirType
     * @return
     */
    @RequestMapping(value = "/up-file",method = RequestMethod.POST ,consumes = "multipart/form-data")
    @ApiOperation(value = "单个图片上传",notes = "单个图片上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name="file",value = "文件流",dataType = "File" ,paramType = "body" ,required = true),
            @ApiImplicitParam(name="dirType",value = "文件夹类型",dataType = "String",paramType = "body",required = false),
            @ApiImplicitParam(name="token",value = "请求头",dataType = "String",paramType = "header",required = true)

    })
    public APIBase upFile(@RequestParam MultipartFile file, String dirType){
        String filePath = "";
        APIBase<Map> ret = new APIBase<Map>();
        try {
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            Random random = new Random();
            String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
            name = ossClientUtils.uploadFile2OSS("",dirType,file.getInputStream(),name); //FileUpload.boostrapUpFile(request, teacher_img_path);
            ret.setCode("0");
            ret.setMsg("上传图片成功");
            filePath = ossClientUtils.getOSS2Url("",dirType,name);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("filePath", filePath);
            ret.setData(jsonObject);
        } catch (FileNotFoundException e) {
            logger.error("上传图片失败"+e.getMessage());
            ret.setMsg("上传图片失败"+e.getMessage());
            ret.setCode(ErrorCode.ERR_BUS_ERROR);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 多图片上传
     * @param files
     * @param dirType
     * @return
     */
    @RequestMapping(value = "/many-up-file",method = RequestMethod.POST)
    public APIBase manyupFile(@RequestParam("files") MultipartFile[] files, String dirType){
        APIBase<Map> ret = new APIBase<Map>();
        try {
            List<String> list = new ArrayList<String>();
            if (files != null && files.length > 0) {
                for (int i = 0; i < files.length; i++) {
                    MultipartFile file = files[i];
                    // 保存文件
                    list = saveFile(file, list,dirType);
                }
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("listPath", list);
            ret.setData(jsonObject);
            ret.setCode("0");
            ret.setMsg("上传图片成功");
        } catch (Exception e) {
            logger.error("上传图片失败:"+e.getMessage());
            ret.setMsg("上传图片失败:"+e.getMessage());
            ret.setCode(ErrorCode.ERR_BUS_ERROR);
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 批量上传图片映射路径
     * @param file
     * @param list
     * @param dirType
     * @return
     */
    private List<String> saveFile(MultipartFile file, List<String> list, String dirType) {
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                if (file.getSize() > 1024 * 1024) {
                    throw new FileNotFoundException("上传图片大小不能超过2M！");
                }
                String originalFilename = file.getOriginalFilename();
                String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
                Random random = new Random();
                String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
                ossClientUtils.uploadFile2OSS("",dirType,file.getInputStream(),name);
                String filePath = ossClientUtils.getOSS2Url("",dirType,name);
                list.add(filePath);
                return list;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }





















































































    @InitBinder
    public void initBinder(WebDataBinder binder){
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
    }

}
